package com.maven.blog.utils;


import com.maven.blog.constant.Constant;
import io.jsonwebtoken.*;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.io.Encoders;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.SecretKey;
import java.security.Key;
import java.util.Date;
import java.util.Map;

@Slf4j
public class JwtsUtils {
    // 这里设置 超时时间
    private static long Expiration=30*60*1000;

    private static String secretString="RfAhvU8rH5q0OcXEkOceztU7fu9dt0X86/1HkwJiAfE=";
    private static SecretKey KEY= Keys.hmacShaKeyFor(Decoders.BASE64.decode(secretString));

    // 设置 token
    public static  String genJwt(Map<String, Object> claims ) {
        String token = Jwts.builder()
                .setClaims(claims)         // 设置载荷
                .signWith(KEY)
                .setExpiration(new Date(System.currentTimeMillis()+Expiration))
                .compact();

        return token;
    }

    //设置密钥
    public void setKey(){
        Key key=Keys.secretKeyFor(SignatureAlgorithm.HS256);
        String encode = Encoders.BASE64.encode(key.getEncoded());
        System.out.println(encode.toString());
    }

    // 解析 token
    public static Claims parseJwt(String token){
        if(token == null){
            return null;
        }
        //创建解析器, 设置签名密钥
        JwtParser jwtParser = Jwts.parser().setSigningKey(KEY);
        //  jwtParser.parseClaimsJws(secretString) : 这里就是解析 获取 token
        Claims claims = null;
        try{
            claims=jwtParser.parseClaimsJws(token).getBody();
        }catch (ExpiredJwtException e) {
            log.error("token过期, 校验失败, token:",token);

        } catch (Exception e) {
            log.error("token校验失败, token:",token);
        }

        return claims;
    }


    public static boolean checkToken(String token){
        Claims body = parseJwt(token);
        if (body==null){
            return false;
        }
        return true;
    }

    public static Integer getUserIdFromToken(String token){
        Claims body = parseJwt(token);
        if (body!=null){
            return (Integer) body.get(Constant.USER_CLAIM_ID);
        }
        return null;
    }
}
